package com.dinero.pagecontents.viewmodel;

import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import androidx.navigation.Navigation
import com.android.basekt.base.BaseViewEventConstants
import com.android.basekt.base.JumpActivityEvent
import com.android.basekt.viewmodel.BaseViewModel
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.ToastUtils
import com.dinero.pagecontents.R
import com.dinero.pagecontents.bean.PersonInfo
import com.dinero.pagecontents.bean.isNetSuccess
import com.dinero.pagecontents.net.ApiClient
import com.dinero.pagecontents.util.PathContants
import com.dinero.pagecontents.util.UserInfoUtils
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import okhttp3.internal.wait
import kotlin.math.ceil

class LoginViewModel : BaseViewModel() {
    var TAG = "LoginViewModel"
    var mPhoneStr = MutableLiveData<String>(UserInfoUtils.getPhone())
    var mDownTimerStr = MutableLiveData<String>()
    var isAgree = MutableLiveData(true)
    var cleanPsw = MutableLiveData(false)

    var isEnableVoiceCode = MutableLiveData(false)
    var finishView = MutableLiveData(false)
    var finishActivity = MutableLiveData(false)

    fun goToMainActivity(personInfo: PersonInfo) {
        Log.i("LoginViewModel", "goToMainActivity: ${personInfo}")
        stopCountDownTimer()
        UserInfoUtils.setSerionId(personInfo.midland)
        UserInfoUtils.setPhone(personInfo.alps)
        finishActivity.value = true
        mViewEvents.value = JumpActivityEvent(PathContants.MAIN_ACTIVITY)
    }


    fun goToLoginCodePage(view: View) {
        if (mPhoneStr.value?.isNotEmpty() == true) {
            var bundle = Bundle()
            bundle.putString("phone", mPhoneStr.value)
            Navigation.findNavController(view)
                .navigate(R.id.action_input_to_code, bundle)
        } else {
            // TODO: 2021/12/15 手机号
            ToastUtils.showShort("Por favor, introduzca el número de teléfono")
        }
    }

    fun getCode(isVoice: Boolean = false) {
        if (!NetworkUtils.isConnected()) {
            ToastUtils.showShort("No internet")
            return
        }
        if (mPhoneStr.value?.isNotEmpty() == true) {
            BaseViewEventConstants.SHOW_LOADING_VIEW.publish()
            viewModelScope.launch {
                if (!NetworkUtils.isConnected()) {
                    ToastUtils.showShort("No internet")
                    return@launch
                }
                var net = netApi {
                    if (isVoice) {
                        ApiClient.instance.getApiService().getVoiceCode(mPhoneStr.value.toString())
                    } else {
                        ApiClient.instance.getApiService().getSmsCode(mPhoneStr.value.toString())
                    }
                }
                var bean = net.await()
                BaseViewEventConstants.DISMISS_VIEW.publish()

                bean?.let {
                    if (!bean.code.isNetSuccess()) {
                        isEnableVoiceCode.value = true
                        ToastUtils.showShort(bean.message)
                    } else {
                        ToastUtils.showShort(bean.message)
                        startCountDownTimer()
                    }
                }
            }
        } else {
            BaseViewEventConstants.DISMISS_VIEW.publish()
        }

    }

    fun checkCode(code: String) {
//        if (BuildConfig.DEBUG) {
//            if (code.isNullOrEmpty() || code.length == 6) {
//                cleanPsw.value = true
//                return
//            }
//        }
        viewModelScope.launch {
            if (code.isNullOrEmpty() || code.length < 6) {
                return@launch
            }

            if (!NetworkUtils.isConnected()) {
                cleanPsw.value = true
                ToastUtils.showShort("No internet")
                return@launch
            }
            BaseViewEventConstants.SHOW_LOADING_VIEW.publish()
            var net = netApi {
                ApiClient.instance.getApiService().smsLogin(mPhoneStr.value.toString(), code)
            }
            var bean = net.await()
            BaseViewEventConstants.DISMISS_VIEW.publish()
            bean?.let {
                if (bean.code.isNetSuccess()) {
                    Log.i(TAG, "checkCode: " + bean)
                    launch {
                        var info = bean.data
                        goToMainActivity(info)
                    }
                } else {
                    cleanPsw.value = true
                    ToastUtils.showShort(bean.message)
                }
            }
        }
    }


    var mCountDownNum = 60
    private val mCountDownTimer: CountDownTimer by lazy {
        object : CountDownTimer(mCountDownNum * 1000L, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                Log.i(TAG, "onTick: ===>$millisUntilFinished")
                var count: Double = (millisUntilFinished - 100) / 1000.toDouble()
                Log.i(TAG, "count: ===>$count")
                var time: Int = ceil(count).toInt()
                Log.i(TAG, "onTick: ===>$time")
                mDownTimerStr.postValue("(${time}s)")

            }

            override fun onFinish() {
                isEnableVoiceCode.value = true
            }
        }
    }


    fun stopCountDownTimer() {
        mCountDownTimer.cancel()
    }

    fun startCountDownTimer() {
        isEnableVoiceCode.value = false
        mCountDownTimer.cancel()
        mCountDownTimer.start()
    }

    fun countDownCoroutines(
        total: Int,
        onTick: (Int) -> Unit,
        onFinish: () -> Unit,
        scope: CoroutineScope = GlobalScope
    ): Job {
        return flow {
            for (i in total downTo 0) {
                emit(i)
                delay(1000)
            }
        }.flowOn(Dispatchers.Default)
            .onCompletion { onFinish.invoke() }
            .onEach { onTick.invoke(it) }
            .flowOn(Dispatchers.Main)
            .launchIn(scope)
    }

    fun jumpAgree() {
        var bundle = Bundle()
        bundle.putString("urlPath", "http://47.88.61.95/#/dineroDeseo")
        JumpActivityEvent(PathContants.WEB_CONTAINER_ACTIVITY, bundle).publish()
    }

    fun agree() {
        isAgree.value = !isAgree.value!!
    }

    fun back(view: View) {
        Navigation.findNavController(view).navigateUp()
    }

    fun hideInput(view: View) {
        KeyboardUtils.hideSoftInput(view)
    }

    override fun finishView() {
        finishView.value = true
    }
}